package com.yuzhyn.hiops.app.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcTool implements AutoCloseable {

    private String url;
    private String user;
    private String password;
    private String driver;
    private Connection conn = null;

    public JdbcTool(String _url, String _user, String _password, String _driver) throws ClassNotFoundException, SQLException {
        this.url = _url;
        this.user = _user;
        this.password = _password;
        this.driver = _driver;
        Class.forName(driver);
        conn = DriverManager.getConnection(url, user, password);
        System.out.println("JdbcTool 连接成功");
    }

    @Override
    public void close() {
        System.out.println("JdbcTool 自动释放资源");
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public List<Map> execute(String sql) throws SQLException {
        try (PreparedStatement statement = conn.prepareStatement(sql)) {
            try (ResultSet rs = statement.executeQuery()) {
                return convertList(rs);
            }
        } catch (Exception ex) {
            throw ex;
        }
    }


    /**
     * 将查询结果resultset转换为List<Map>
     *
     * @param rs
     * @return
     * @throws SQLException
     */
    private static List<Map> convertList(ResultSet rs) throws SQLException {
        List<Map> list = new ArrayList<>();
        //获取键名
        ResultSetMetaData md = rs.getMetaData();
        //获取列的数量
        int columnCount = md.getColumnCount();
        while (rs.next()) {
            //声明Map
            Map<String, Object> rowData = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                //获取键名及值
                rowData.put(md.getColumnName(i), rs.getObject(i));
            }
            list.add(rowData);
        }
        return list;
    }

//    public void Select(){}
//
//    public void Select(){}
//
//    public void Select(){}
}
